<?php
/**
 * Define the Nugget Management class
 */
class NuggetManagement
{
	var $NuggetFile = 'nugget.php';
	var $Nugget = 0;
	var $Position = array(0 => array('name' =>'[Frozen]'		,'position' => '[Frozen]'),
			      1 => array('name' =>'Head tag'		,'position' => 'HEADER'),
			      2 => array('name' =>'Above Banner'	,'position' => 'CONTROL_POSITION_HEAD'),
			      3 => array('name' =>'Menu'		,'position' => 'CONTROL_POSITION_MENU'),
			      4 => array('name' =>'Below Banner'	,'position' => 'CONTROL_POSITION_BANNER'),
			      5 => array('name' =>'Above Content'	,'position' => 'CONTROL_POSITION_PANEL'),
			      6 => array('name' =>'Below Content'	,'position' => 'CONTROL_POSITION_BODY_ITEM'),
			      7 => array('name' =>'Footer'		,'position' => 'CONTROL_POSITION_FOOT'),
			      8 => array('name' =>'Inside Panel'	,'position' => 'PANEL'),
			      9 => array('name' =>'Below Panel'		,'position' => 'BELOW_PANEL'),
			      10 => array('name' =>'In Comments'	,'position' => 'COMMENT'));

	var $Pages = array(0 => array('name' => 'Comment List'          ,'page' =>'comments.php'),
			   1 => array('name' => 'Discussion List'       ,'page' =>'index.php'),
			   2 => array('name' => 'Settings Page'         ,'page' =>'settings.php'),
			   3 => array('name' => 'Account Page'          ,'page' =>'account.php'),
			   4 => array('name' => 'Post Comment'          ,'page' =>'post.php'),
			   5 => array('name' => 'Search Page'           ,'page' =>'search.php'),
			   6 => array('name' => 'Categories Page'       ,'page' =>'categories.php'));

	var $Weight = array('min' => -10, 'max' => 10);
	var $Roles = array();
	var $PositionCount = array('HEADER' => 0, // To speed up the code, find out how many Positions are there and which ones, and whether looping through the Nuggets is even needed
				   'CONTROL' => 0,
				   'COMMENT' => 0);
	var $SentNuggetID, $NuggetIndex = -1;

	/**
	* Constructor
	*/
	function NuggetManagement(&$Context)
	{
		$this->NuggetFile = './extensions/Nugget/'.$this->NuggetFile;
		$this->Context = &$Context;
		// Store result from nugget.php file
		$this->Nugget = $this->GetNuggetList();
		$this->GetPositionCount();

		$this->SentNuggetID = ForceIncomingString('NuggetID', '');
		if(!empty($this->SentNuggetID) && is_array($this->Nugget))
		{
			for($i = 0; $i < count($this->Nugget); $i++)
			{
				if($this->Nugget[$i]['id'] == $this->SentNuggetID) {$this->NuggetIndex = $i; break;}

			}
		}
	}

	/**
	* Read the NuggetFile
	*/
	function GetNuggetList()
	{
		if(file_exists($this->NuggetFile)) return include($this->NuggetFile);
		else return 0;
	}
	/**
	* Get Position count
	*/
	function GetPositionCount()
	{

		for ($i = 0; $i < count($this->Nugget); $i++)
		{
			if ($this->Nugget[$i]['status']) {
				if ($this->Nugget[$i]['position'] == 'HEADER') $this->PositionCount['HEADER']++;
				else if ($this->Nugget[$i]['position'] == 'COMMENT') $this->PositionCount['COMMENT']++;
				else $this->PositionCount['CONTROL']++;
			}
		}
	}
	/**
	* Format the Nugget Array in an appropriate form
	*/
	function FormatArray($Arr)
	{
		$NewArr = array();
		while(list($Index, $Value) = each($Arr))
		{
			$NewElement = (is_numeric($Index) ? $Index : ('\''.str_replace("'", "\\'", $Index).'\'')).' => ';
			if(is_array($Value)) $NewElement .= $this->FormatArray($Value);
			else $NewElement .= (is_numeric($Value) ? $Value : ('\''.str_replace("'", "\\'", $Value).'\''));
			$NewArr[] = $NewElement;
		}
		$NewArr = 'array('.implode(', ', $NewArr).')';

		return $NewArr;
	}
	/**
	* Save the Nugget to the file
	*/
	function SaveNugget()
	{
		//Sort Array before saving
		usort($this->Nugget, 'NuggetSort');
		for ($i = 0; $i < count($this->Nugget); $i++) {
			$this->Nugget[$i]['id'] = $i+1;
		}

		$fd = @fopen($this->NuggetFile, 'wb');

		$r = 1;
		if($fd)
		{
			$Buffer = '<?php return '.$this->FormatArray($this->Nugget).'; ?>';

			for($i = 0; !flock($fd, LOCK_EX) && $i <= 3; $i++) sleep(1);
			if($i <= 3)
			{
				if(@fwrite($fd, $Buffer) !== FALSE) $r = 0;
				flock($fd, LOCK_UN);
				fclose($fd);
			}
		}

		if($r)
		{
			//whoops...
			if(file_exists($this->NuggetFile)) unlink($this->NuggetFile);
			echo('<span style="font-weight: bold; color: #f00;">'.
			sprintf($this->Context->GetDefinition('NuggetObj_FileError'), $this->NuggetFile).
			'</span>');
		}

		return;
	}
	/**
	* Save new weight and position values
	*/
	function SaveNuggetList()
	{
		while(list($NuggetIndex, $arr) = each($_POST) )
		{
			if (is_numeric($NuggetIndex))
			{

				$Name = $this->Nugget[$NuggetIndex]['name'];
				$ID = $this->Nugget[$NuggetIndex]['id'];
				$HTML = $this->Nugget[$NuggetIndex]['html'];
				$Description = $this->Nugget[$NuggetIndex]['description'];
				$HideName = $this->Nugget[$NuggetIndex]['hideName'];
				$RoleArr = $this->Nugget[$NuggetIndex]['roles'];
				$PagesArr = $this->Nugget[$NuggetIndex]['pages'];
				$Position = $arr['Position'];
				$Weight = $arr['Weight'];

				$this->Nugget[$NuggetIndex] = array(
				'name' => $Name,
				'id' => $ID,
				'description' => $Description,
				'position' => $Position,
				'status' => $Position == '[Frozen]' ? 0 : 1,
				'hideName' => $HideName,
				'html' => $HTML,
				'weight' => $Weight,
				'roles' => $RoleArr,
				'pages' => $PagesArr
				);
			}
		}
		$this->SaveNugget();
		return 0;

	}
	/**
	* Create the Nugget coming from New/Edit Nugget page and save the result back in the file
	*/
	function CreateNugget(&$NuggetSettings)
	{
		$Name = ForceIncomingString('Name', '');
		$ID = ForceIncomingInt('ID', 0);
		$HTML = ForceIncomingString('HTML', '');
		$Description = ForceIncomingString('Description', '');
		$Position = ForceIncomingString('Position', '');
		$HideName = ForceIncomingBool('HideName', 0);
		$Weight = ForceIncomingInt('Weight', 0);
		$RoleArr = ForceIncomingArray('AllowedRoles', array());
		$PagesArr = ForceIncomingArray('AllowedPages', array());
		/*while (list(,$Value) = each($PagesArr))
		{
			if (!in_array($Value, array("settings.php","search.php","account.php","index.php","comments.php","post.php","categories.php")))
			{
				$PagesArr = array_merge($PagesArr, array("extension.php"));
				break;
			}
		}*/

		//so the user won't lose any info on error
		$NuggetSettings->NuggetName = htmlspecialchars($Name);
		$NuggetSettings->NuggetHTML = htmlspecialchars($HTML);
		$NuggetSettings->NuggetID = $ID;
		$NuggetSettings->NuggetPosition = htmlspecialchars($Position);
		$NuggetSettings->NuggetDescription = htmlspecialchars($Description);
		$NuggetSettings->NuggetWeight = $Weight;
		$NuggetSettings->NuggetRoles = $RoleArr;
		$NuggetSettings->NuggetPages = $PagesArr;
		$NuggetSettings->NuggetHideName = $HideName;

		if(!strlen($Name))
		{
			$this->Context->WarningCollector->Add($this->Context->GetDefinition('NuggetObj_NoInputValue'));
			return 1;
		}


		if($ID == '') $ID = 100; //arbitrary high number

		for($i = $f = 0; $i < count($this->Nugget); $i++)
		{
			if($this->Nugget[$i]['id'] == $ID && $i != $this->NuggetIndex)
			{
				$f = 1; //Nugget already exists
				break;
			}
		}
		if($f)
		{
			//Display error, since nugget already exists.
			$this->Context->WarningCollector->Add($this->Context->GetDefinition('NuggetObj_AlreadyCreated'));
			return 1;
		}

		$NewNugget = array(
			'name' => $Name,
			'id' => $ID,
			'description' => $Description,
			'position' => $Position,
			'status' => $Position =='[Frozen]' ? 0 : 1,
			'hideName' => $HideName,
			'html' => $HTML,
			'weight' => $Weight,
			'roles' => $RoleArr,
			'pages' => $PagesArr
		);

		if(isset($this->Nugget[$this->NuggetIndex])) //Overwrite existing nugget
			$this->Nugget[$this->NuggetIndex] = $NewNugget;
		else // Add a new Nugget
			$this->Nugget[count($this->Nugget)] = $NewNugget;

		$this->SaveNugget();

		return 0;
	}
	/**
	* Remove the Nugget and save the result back in the file
	*/
	function RemoveNugget()
	{
		if(isset($this->Nugget[$this->NuggetIndex]))
		{
			unset($this->Nugget[$this->NuggetIndex]);
			$this->Nugget = array_values($this->Nugget);
			$this->SaveNugget();
		}
	}

}
?>
